package aop;

import java.util.List;
import java.util.Set;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import first.guodao.annotation.Guodao;

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	private List<String> packagesToScan;

	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {
		try {
			// 循环传入的MiniDao配置
			for (String pack : packagesToScan) {
				if (org.apache.commons.lang.StringUtils.isNotEmpty(pack)) {
					Set<Class<?>> classSet = PackagesToScanUtil
							.getClasses(pack);
					for (Class<?> guodaoClass : classSet) {
						if (guodaoClass.isAnnotationPresent(Guodao.class)) {
							// 单独加载一个接口的代理类
							ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
							proxyFactoryBean.setBeanFactory(beanFactory);
							proxyFactoryBean
									.setInterfaces(new Class[] { guodaoClass });
							proxyFactoryBean
									.setInterceptorNames(new String[] {"myMethodInterceptor"});
							String beanName = getFirstSmall(guodaoClass
									.getSimpleName());
							if (!beanFactory.containsBean(beanName)) {
								beanFactory.registerSingleton(beanName,
										proxyFactoryBean.getObject());
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	/**
	 * @return the packagesToScan
	 */
	public List<String> getPackagesToScan() {
		return packagesToScan;
	}

	/**
	 * @param packagesToScan
	 *            the packagesToScan to set
	 */
	public void setPackagesToScan(List<String> packagesToScan) {
		this.packagesToScan = packagesToScan;
	}

	public static String getFirstSmall(String name) {
		name = name.trim();
		if (name.length() >= 2) {
			return name.substring(0, 1).toLowerCase() + name.substring(1);
		} else {
			return name.toLowerCase();
		}

	}
}
